package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.service.api.MenuService;
import com.atguigu.crowd.util.ResultEntity;
import entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;

@Controller
public class MenuHandler {
    @Autowired
    private MenuService menuService;

    @ResponseBody
    @RequestMapping("menu/do/get.json")
    public ResultEntity<Menu> getWholeTreeNew() {
        //1. 查询所有的Menu对象
        List<Menu> menuList = menuService.getAll();
        for (Menu menu : menuList) {
            System.out.println("menu对象是"+menu);
        }
        //2. 声明一个变量来存储根节点
        Menu root = null;
        //3. 创建Map 对象来创建存储id和Menu对象的对应关系便于查找父节点
        HashMap<Integer, Menu> menuMap = new HashMap<>();
        //4. 遍历 menuList 填充 menuMap
        for (Menu menu : menuList) {
            Integer id = menu.getId();
            menuMap.put(id, menu);
        }
        //5. 再次遍历 menuList 查找根节点、组装父子节点
        for (Menu menu : menuList) {
            //6. 获取当前 menu 对象的 pid 属性值
            Integer pid = menu.getPid();
            //7. 如果pid为null判断根节点
            if(pid==null){
               root=menu;
           //8. 如果当前节点是根节点那么肯定没有父节点不必继续执行
                continue;
            }
            //9. 如果 pid 不为 null，说明当前节点有父节点，那么可以根据 pid 到 menuMap 中查找对应的 Menu 对象
            Menu father = menuMap.get(pid);
            //10. 将当前节点存入父节点的 children 集合
            father.getChildren().add(menu);
        }
        return ResultEntity.successWthData(root);
    }

    @ResponseBody
    @RequestMapping("menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu){

        menuService.saveMenu(menu);

        return ResultEntity.successWthoutData();
    }

    @ResponseBody
    @RequestMapping("menu/edit.json")
    public ResultEntity<String> editMenu(Menu menu){
        menuService.editMenu(menu);
        return ResultEntity.successWthoutData();
    }
    @ResponseBody
    @RequestMapping("menu/remove.json")
    public ResultEntity<String> removeMenu(Integer id){
        menuService.removeMenuById(id);
        return ResultEntity.successWthoutData();
    }
}
